<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="网关SN" prop="gatewaySn">
        <el-input
          v-model="queryParams.gatewaySn"
          placeholder="请输入网关SN"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="管养单位" prop="deptId" style="width: 260px;">
        <el-select v-model="queryParams.deptId" placeholder="请选择管养单位" clearable>
          <el-option
            v-for="dict in sys_dept_list"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['slope:gateway:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['slope:gateway:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['slope:gateway:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['slope:gateway:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="gatewayList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="网关SN" align="center" prop="gatewaySn" />
      <el-table-column label="A报警设备ID" align="center" prop="deviceA" />
      <el-table-column label="B报警设备ID" align="center" prop="deviceB" />
      <el-table-column label="管养单位" align="center" prop="deptId" width="200px">
        <template #default="scope">
          <dict-tag :options="sys_dept_list" :value="scope.row.deptId"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="网关信息" align="center" prop="gatewayInfo" />
      <el-table-column label="网关电量" align="center" prop="batteryCharge" />
      <el-table-column label="网关状态" align="center" prop="gatewayOnline">
        <template #default="scope">
          <dict-tag :options="slope_gateway_state" :value="scope.row.gatewayOnline"/>
        </template>
      </el-table-column>
      <el-table-column label="报警开关状态" align="center" prop="alarmSwitch">
        <template #default="scope">
          <dict-tag :options="alarm_switch" :value="scope.row.alarmSwitch"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['slope:gateway:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['slope:gateway:remove']">删除</el-button>
          <el-button link type="primary" icon="Edit" @click="scope.row.alarmSwitch === 0 ? handleAlarm(scope.row) : handleCancelAlarm(scope.row)" v-hasPermi="['slope:gateway:edit']">
            {{ scope.row.alarmSwitch === 0 ? '声光报警' : '解除报警' }}
          </el-button>
          <el-button link type="primary" icon="Edit" @click="soundDeviceAlarm(scope.row)" v-hasPermi="['slope:gateway:edit']">
            喇叭报警
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdateData(scope.row)" v-hasPermi="['slope:gateway:edit']">更新采样数据</el-button>
          <el-button link type="primary" icon="Edit" @click="openDialog(scope.row)" v-hasPermi="['slope:gateway:edit']">更新采样时间</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="更新采样时间" v-model="dialogVisible" width="40%">
      <el-form>
        <el-form-item label="采样时间（1-120）分钟" >
          <el-input-number
              style="width: 200px;"
              v-model="inputValue"
              :min="1"
              :max="120"
              :step="1"
              controls-position="right"
              placeholder="输入1-120的整数"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmUpdate">确定</el-button>
    </span>
    </el-dialog>

    <!-- 添加或修改边坡网关信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="gatewayRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="网关SN" prop="gatewaySn">
          <el-input v-model="form.gatewaySn" placeholder="请输入网关SN" />
        </el-form-item>
        <el-form-item label="A报警设备" prop="deviceA">
          <el-input v-model="form.deviceA" placeholder="请输入网关SN" />
        </el-form-item>
        <el-form-item label="B报警设备" prop="deviceB">
          <el-input v-model="form.deviceB" placeholder="请输入网关SN" />
        </el-form-item>
        <el-form-item label="管养单位" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择管养单位">
            <el-option
              v-for="dict in sys_dept_list"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="网关信息" prop="gatewayInfo">
          <el-input v-model="form.gatewayInfo" placeholder="请输入网关信息" />
        </el-form-item>
        <el-form-item label="网关状态" prop="gatewayOnline">
          <el-select v-model="form.gatewayOnline" placeholder="请选择网关状态">
            <el-option
              v-for="dict in slope_gateway_state"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警开关状态" prop="alarmSwitch">
          <el-select v-model="form.alarmSwitch" placeholder="请选择报警开关状态">
            <el-option
              v-for="dict in alarm_switch"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Gateway">
import { soundAlarm, listGateway, getGateway, delGateway, addGateway, updateGateway, alarm, getData, getDataTime, cancelAlarm } from "@/api/slope/gateway/gateway.js";
import { ElLoading,ElMessage  } from 'element-plus'

const { proxy } = getCurrentInstance();
const { alarm_switch, sys_dept_list, slope_gateway_state } = proxy.useDict('alarm_switch', 'sys_dept_list', 'slope_gateway_state');

const dialogVisible = ref(false);
const inputValue = ref(null);
const currentRow = ref(null);

const gatewayList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    gatewaySn: null,
    deptId: null,
  },
  alarmParams:{
    gatewaySn: null,
    time: null
  },
  rules: {
    gatewaySn: [
      { required: true, message: "网关SN不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "管养单位不能为空", trigger: "change" }
    ],
  }
});

const { alarmParams, queryParams, form, rules } = toRefs(data);

function openDialog(row) {
  currentRow.value = row;
  inputValue.value = null;  // 每次打开清空
  dialogVisible.value = true;
}

function confirmUpdate(){
  dialogVisible.value = false;
  handleUpdateTime(currentRow.value,inputValue.value)
}

async function handleAlarm(row) {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '报警中，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    alarmParams.value.gatewaySn = row.gatewaySn;
    await alarm(alarmParams.value); // 必须是 async 函数或返回 Promise
    ElMessage.success('报警成功'); // ✅ 勾号提示
    getList();
  } catch (error) {
    ElMessage.error('报警失败');
  } finally {
    loading.close();
  }
}

async function handleCancelAlarm(row) {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '解除报警中，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    alarmParams.value.gatewaySn = row.gatewaySn;
    await cancelAlarm(alarmParams.value);
    ElMessage.success('报警已解除');
    getList();
  } catch (error) {
    ElMessage.error('解除报警失败');
    console.error(error);
  } finally {
    loading.close();
  }
}

async function handleUpdateData(row) {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '更新采样数据中，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    alarmParams.value.gatewaySn = row.gatewaySn;
    await getData(alarmParams.value);
    ElMessage.success('采样数据更新成功');
  } catch (error) {
    ElMessage.error('采样数据更新失败');
    console.error(error);
  } finally {
    loading.close();
  }
}


async function handleUpdateTime(row, inputValue) {
  const loading = ElLoading.service({
    fullscreen: true,
    text: '更新时间中，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    alarmParams.value.gatewaySn = row.gatewaySn;
    alarmParams.value.time = inputValue.toString(16).padStart(2, '0');
    await getDataTime(alarmParams.value);
    ElMessage.success('采样时间更新成功');
  } catch (error) {
    ElMessage.error('采样时间更新失败');
    console.error(error);
  } finally {
    loading.close();
  }
}


/** 查询边坡网关信息列表 */
function getList() {
  loading.value = true;
  listGateway(queryParams.value).then(response => {
    gatewayList.value = response.rows;
    console.log(gatewayList)
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    gatewaySn: null,
    deptId: null,
    updateTime: null,
    gatewayInfo: null,
    gatewayOnline: null,
    alarmSwitch: null,
    deviceA: null,
    deviceB: null,
  };
  proxy.resetForm("gatewayRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加边坡网关信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getGateway(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改边坡网关信息";
  });
}

async function soundDeviceAlarm(data) {
  try {
    await soundAlarm(data);
    getList();
    ElMessage.success("报警成功")
  } catch (error) {
    ElMessage.error("报警失败，请联系管理员");
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["gatewayRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateGateway(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGateway(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除边坡网关信息编号为"' + _ids + '"的数据项？').then(function() {
    return delGateway(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('slope/gateway/export', {
    ...queryParams.value
  }, `gateway_${new Date().getTime()}.xlsx`)
}

getList();
</script>
